package project.suntray.com.core.net.callback;


import android.os.Handler;

import commerce.zhangyang.com.core.app.ConfigureType;
import commerce.zhangyang.com.core.app.Natte;
import commerce.zhangyang.com.core.net.RestCreator;
import retrofit2.Callback;

/**
 * Created by zhangyang on 2017/12/18 05:59.
 * version 1
 *  接口请求的回调!
 */
public class ReqeustsCallBack implements Callback<String> {

    private final IRequest REQUEST;
    private final ISuccess SUCCESS;
    private final IFailure FAILURE;
    private final IError ERROR;
    private final Handler HANDLER= Natte.getConfiguration(ConfigureType.HANDLER.name());

    public ReqeustsCallBack(IRequest REQUEST, ISuccess SUCCESS, IFailure FAILURE, IError ERROR) {
        this.REQUEST = REQUEST;
        this.SUCCESS = SUCCESS;
        this.FAILURE = FAILURE;
        this.ERROR = ERROR;
    }

    @Override
    public void onResponse(retrofit2.Call<String> call, retrofit2.Response<String> response) {

        //判断是否成功
        if(response!=null && response.isSuccessful()){
            if (SUCCESS!=null)
                SUCCESS.onSuccess(response.body());
        }else{
            if (ERROR!=null)
                ERROR.onError(response.code(),response.message());
        }
    }

    @Override
    public void onFailure(retrofit2.Call<String> call, Throwable t) {
        if (FAILURE!=null)
             FAILURE.onFailure("请求接口失败!");

        if(REQUEST!=null)
            REQUEST.onRequestEnd();

        //请求结束
        requestFinish();
    }

    /**
     * 请求结束 停止加载
     */
    private void requestFinish() {
        HANDLER.postDelayed(new Runnable() {
            @Override
            public void run() {
                //去除参数
                RestCreator.getParams().clear();
                //停止加载:

            }
        },(int)Natte.getConfiguration(ConfigureType.LOAD_DELAY.name()));
    }
}
